<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/8/31
 * Time: 11:34
 */
namespace app\admin\controller;

use app\BaseController;
use app\middleware\AdminCheck;
use think\facade\Db;

class Menu extends BaseController{

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [] ]
    ];


    /**
     * 所有菜单的树状结构
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function menuList(){
        $list=Db::name('system_menu')
            ->order('sort desc')
            ->select()->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['meta']=json_decode($v['meta'],true);
        }
        $menu=getMenuTree($list);

        return success('所有菜单的树状结构',$menu);
    }


    /**
     * 菜单的添加
     * @return \think\response\Json
     */
    public function add(){
        //redirect,alwaysShow,dot,hidden(这些参数不是必填的)
        validateParam('parentId,name,path,component,meta','parentId,name,path,component,meta');
        $data=input();
        $data['meta']=json_encode($data['meta']);
        $data['update_at']=currentTime();
        $data['create_at']=currentTime();
        Db::name('system_menu')->insert($data);
        return success('添加菜单成功');
    }


    /**
     * 编辑菜单
     * @return \think\response\Json
     */
    public function edit(){
        //redirect,alwaysShow,dot,hidden(这些参数不是必填的)
        validateParam('id,parentId,name,path,component,meta','id,parentId,name,path,component,meta');
        $data=input();
        $data['update_at']=currentTime();
        $data['meta']=json_encode($data['meta']);
        unset($data['children']);
        Db::name('system_menu')
            ->save($data);
        return success('编辑菜单成功');
    }


    /**
     * 删除菜单
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete(){
        validateParam('id','id');
        Db::name('system_menu')
            ->where(['id'=>input('id')])
            ->delete();
        return success('删除菜单成功');
    }


    /**
     * 菜单设置权重
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function sort(){
        validateParam('id,number','id,number');
        $param=input();
        Db::name('system_menu')
            ->where('id','=',$param['id'])
            ->update(['sort'=>$param['number']]);
        return success('设置权重成功');
    }

}